package de.ifgi.tank;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

import android.app.Activity;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

/**
 * This Class provides the UDP receiving functionality of the App. It receives
 * an UDP Packet from the Arduino which information is used to update the tank
 * image in real time.
 * 
 * @author matthias.robbers@wwu.de
 * 
 */

public class UDPReceive {
	private Activity activity;
	private int port;
	private DatagramSocket dsocket;

	public UDPReceive(Activity activity, int port) {
		this.activity = activity;
		this.port = port;
		receive();
	}

	private void receive() {
		new Thread() {
			@Override
			public void run() {
				super.run();
				try {
					dsocket = new DatagramSocket(port);
					byte[] message = new byte[1024];
					while (true) {
						DatagramPacket p = new DatagramPacket(message,
								message.length);
						Log.d("UDP", "Receiving...");
						dsocket.receive(p);
						String text = new String(message, 0, p.getLength());
						Log.d("UDP", text.trim());
						Message msg = new Message();
						if (text.trim().equals("lf"))
							msg.what = 1;
						else if (text.trim().equals("mf"))
							msg.what = 2;
						else if (text.trim().equals("rf"))
							msg.what = 3;
						else if (text.trim().equals("lb"))
							msg.what = 4;
						else if (text.trim().equals("mb"))
							msg.what = 5;
						else if (text.trim().equals("rb"))
							msg.what = 6;
						else if (text.trim().equals("00"))
							msg.what = 7;
						else if (text.trim().equals("start"))
							msg.what = 8;
						else if (text.trim().equals("stop"))
							msg.what = 9;
						handler.sendMessage(msg);
					}
				} catch (SocketException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

			private Handler handler = new Handler() {
				@Override
				public void handleMessage(Message msg) {
					if (msg.what > 0 && msg.what <= 7) {
						((MainActivity) activity).updateWarnings(msg.what);
					} else if (msg.what == 8) {
						((MainActivity) activity).startTankView();
					} else if (msg.what == 9) {
						((MainActivity) activity).stopTankView();
					}
				}
			};
		}.start();
	}

	public void stop() {
		if (dsocket != null) {
			dsocket.close();
		}
	}
}
